from flask import (session)
from flaskr.Utils import *
import os

nowDir = os.path.abspath(os.path.dirname(__file__))
path = os.path.abspath(os.path.join(nowDir, ".."))

def get_sheets():
    if 'sheets' not in session.keys():
        session['sheets'] = []

    sheets = session['sheets']

    return sheets


def get_sheet(sheet_name):
    sheets = get_sheets()

    for sheet in sheets:
        if sheet['showName'] == sheet_name:
            return sheet

    return None

def has_pkl(sheet_name):
    sheet = get_sheet(sheet_name)

    if sheet is not None and 'md5' in sheet.keys() and sheet['md5'] is not None:
        return True

    return False

#是否存在这个pkl文件
def has_pkl_file(filename):
    pkl_file_path = path + '/cache_file/' + filename + '.pkl'

    res = os.path.exists(pkl_file_path)
    return res

def get_sheet_md5(sheet_name):
    sheet = get_sheet(sheet_name)
    md5 = sheet['md5'].split('_')[0]

    return md5

def get_dataframe_by_pkl(sheet_name):
    sheet = get_sheet(sheet_name)

    if not sheet or not has_pkl(sheet_name):
        return None

    try:
        df = pandas.read_pickle(path + '/cache_file/' + sheet['md5'] + '.pkl')
    except IOError as e:
        print(e)
        df = None

    return df


def get_dataframe_by_json(sheet_name):
    sheet = get_sheet(sheet_name)

    if not sheet or 'json' not in sheet.keys():
        return None

    return jsonToDataFrame(sheet['json'])

def get_dataframe(sheet_name):
    sheet = get_sheet(sheet_name)

    if sheet:
        if has_pkl(sheet_name):
            return get_dataframe_by_pkl(sheet_name)

        else:
            return get_dataframe_by_json(sheet_name)

    return None

def remove_sheet(sheet_name):
    sheets = get_sheets()
    for i in range(len(sheets)):
        if sheets[i]['showName'] == sheet_name:
            sheets.pop(i)
            --i
            session['sheets'] = sheets

def set_sheet(sheet_name, val):
    sheets = get_sheets()
    for i in range(len(sheets)):
        if sheets[i]['showName'] == sheet_name:
            sheets[i] = val
            session['sheets'] = sheets



